package com.example.zjx8969.myapplication;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;



import java.util.Locale;

/**
 * 启用了JavaScriptEnabled | 处理yhouse:// | UserAgent 中添加了YhouseAppVersion
 * Created by hawk.zheng on 2015/10/14.
 */
public class CustomizationWebView extends WebView {

    public CustomizationWebView(Context context) {
        super(context);
        init();
    }

    public CustomizationWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public void init() {
        if (isInEditMode()) return;
//        CommUtil.syncCookie(getContext());
        WebSettings settings = this.getSettings();
        settings.setJavaScriptEnabled(true);
        setBackgroundColor(Color.argb(1, 0, 0, 0));
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            settings.setMixedContentMode(android.webkit.WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

        settings.setDomStorageEnabled(true);
        settings.setLoadWithOverviewMode(true);
        settings.setUseWideViewPort(true);
//        settings.setLoadsImagesAutomatically(false);
//        if (NetworkUtil.checkNetwork(getContext())) {
//            settings.setCacheMode(WebSettings.LOAD_DEFAULT);
//        } else {
//            // 设置 缓存模式             在LOAD_CACHE_ELSE_NETWORK模式下，无论是否有网络，只要本地有缓存，都使用缓存。本地没有缓存时才从网络上获取。
//            settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
//        }
        // 开启 database storage API 功能
        settings.setDatabaseEnabled(true);
        // 开启 Application Caches 功能
        settings.setAppCacheEnabled(true);

//        String userAgent = YhouseHttpHeaderHolder.getInstance().setSystemWebViewUserAgent(settings.getUserAgentString());//OkHttpClientManager.freshUserAgent(settings.getUserAgentString());
//        settings.setUserAgentString(userAgent);

        settings.setRenderPriority(WebSettings.RenderPriority.HIGH);

        setWebViewClient(new WebViewClient() {
            String failedUrl;

            @Override
            public void onReceivedError(WebView webView, int i, String s, String s1) {
                super.onReceivedError(webView, i, s, s1);
                failedUrl = s;
            }


            @Override
            public void onLoadResource(WebView view, String url) {
                super.onLoadResource(view, url);
//                logContent("onLoadResource>" + url);
            }

            @Override
            public void onReceivedSslError(WebView webView, SslErrorHandler sslErrorHandler, SslError sslError) {
                super.onReceivedSslError(webView, sslErrorHandler, sslError);
                sslErrorHandler.proceed();
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                view.setEnabled(false);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                view.setEnabled(true);
//                getSettings().setLoadsImagesAutomatically(true);
                if (!url.toLowerCase().startsWith("http"))
                    return;//避免锤子等手机在webView加载失败后自行加载了一个默认的本地错误HTML
                if (webViewClientDelegate != null) {
                    webViewClientDelegate.webViewPageLoadFinish(view, url, !TextUtils.equals(failedUrl, url));
                }
                failedUrl = null;
            }


            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (shouldOverride != null) {
                    boolean status = shouldOverride.shouldOverrideUrl(url);
                    if (status) return true;
                }
                if (!TextUtils.isEmpty(url) && url.startsWith("yhouse")) {
                    Uri uri = Uri.parse(url);
                    if (TextUtils.isEmpty(uri.getHost())) return true;
                    if (!TextUtils.isEmpty(uri.getQuery())) {
                        String campaign = uri.getQueryParameter("pk_campaign");
                        String kwd = uri.getQueryParameter("pk_kwd");

                    }
//                    AppRouter.getInstance().route(getContext(), url, null);
                } else if (url.startsWith("tel:")) {
                    Intent diaIntent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
                    getContext().startActivity(diaIntent);
                } else if (url.startsWith("mailto:")) {
                    String[] reciver = new String[]{"businesschina@yhouse.com"};
                    Intent mailIntent = new Intent(Intent.ACTION_SEND, Uri.parse(url));
                    mailIntent.putExtra(Intent.EXTRA_EMAIL, reciver);
                    mailIntent.setType("message/rfc822");
//                    try {
//                        getContext().startActivity(Intent.createChooser(mailIntent, getContext().getString(R.string.select_mail)));
//                    } catch (android.content.ActivityNotFoundException ex) {
//                        Toast.makeText(getContext(), "There are no email clients installed.", Toast.LENGTH_SHORT).show();
//                    }
                } else if (url.startsWith("http")) {
                    return super.shouldOverrideUrlLoading(view, url);
                } else {
                    Intent intent = new Intent();
                    intent.setData(Uri.parse(url));
//                    boolean intentAvailable = CommUtil.isIntentAvailable(view.getContext(), intent);
//                    if (intentAvailable) {
//                        view.getContext().startActivity(intent);
//                    }
                }
                return true;
            }
        });
//        IX5WebViewExtension x5WebViewExtension = getX5WebViewExtension();//禁用滚动条
//        if (x5WebViewExtension != null) {
//            x5WebViewExtension.setScrollBarFadingEnabled(false);
//        }
    }

//    public void logContent(String content) {
//        if (BuildConfig.DEBUG) {
//            Log.e("webView", content);
//        }
//    }

    /**
     * 直接调用setWebChromeClient会被growingIO替换掉
     *
     * @param webChromeClient
     */
    public void setWebViewChromeClient(WebChromeClient webChromeClient) {
        setWebChromeClient(webChromeClient);
    }

    public void setShouldOverride(ShouldOverrideUrl overrideUrl) {
        this.shouldOverride = overrideUrl;
    }

    ShouldOverrideUrl shouldOverride;//Override

    public interface ShouldOverrideUrl {
        boolean shouldOverrideUrl(String url);
    }

    private WebViewClientDelegate webViewClientDelegate;

    public void setWebViewClientDelegate(WebViewClientDelegate delegate) {
        this.webViewClientDelegate = delegate;
    }

    public interface WebViewClientDelegate {
        void webViewPageLoadFinish(WebView view, String url, boolean isSuccess);

//        void onWebPageLoadError();
    }


    public void onActivityPause() {
        onPause();
    }

    public void onActivityResume() {
        onResume();
    }


    public void onActivityDestroy() {
        loadUrl("about:blank");
//        stopLoading();
        removeAllViews();
        destroy();
    }

    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        super.onScrollChanged(l, t, oldl, oldt);
        if (onScrollChangedCallback != null) onScrollChangedCallback.onScroll(l, t);
    }

    public void setOnScrollChangedCallback(OnScrollChangedCallback onScrollChangedCallback) {
        this.onScrollChangedCallback = onScrollChangedCallback;
    }

    private OnScrollChangedCallback onScrollChangedCallback;

    public interface OnScrollChangedCallback {
        void onScroll(int l, int t);
    }

    public void loadJs(String jsMethod) {
        if (TextUtils.isEmpty(jsMethod)) return;
        loadUrl(String.format(Locale.getDefault(), "javascript:%s()", jsMethod));
    }
}
